const fs = require('fs');
const path = require('path');

let oldHtml = path.join(__dirname, 'index.html');
let newHtml = path.join(__dirname, 'abc-02', 'index.html');
let cssPath = path.join(__dirname, 'abc-02', 'index.css');
let jsPath = path.join(__dirname, 'abc-02', 'index.js');

fs.readFile(oldHtml, 'utf-8', (err, data) => {
    if (err) return console.log(err);

    let cssReg = /<style>([\s\S]*)<\/style>/g;
    let cssResult = cssReg.exec(data);
    console.log(cssResult[1]);
    fs.writeFile(cssPath, cssResult[1], err => {
        if (err) return console.log(err);
        console.log('css分离成功');
    });

    let jsReg = /<script>([\s\S]*)<\/script>/g;
    let jsResult = jsReg.exec(data);
    console.log(jsResult[1]);
    fs.writeFile(jsPath, jsResult[1], err => {
        if (err) return console.log(err);
        console.log('js分离成功');
    });

    data = data.replace(cssReg, '<link rel="stylesheet" href="index.css">');
    data = data.replace(jsReg, '<script src="index.js"></script>');

    fs.writeFile(newHtml, data, err => {
        if (err) return console.log(err);
        console.log('html保存成功');
    })
});